<template>
  <div class="view-fill">
    <div v-show="!assetDetailInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :needReturn="!flowFormType"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button
            :disabled="!canSave"
            @click="saveAndSubmit()"
            v-if="
              !id && $permission('assetDeal:saveAndSubmit') && !flowFormType
            "
            >保存并提交</el-button
          >
          <el-button v-if="!flowFormType" :disabled="!canSave" @click="save()"
            >保存</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addProduct>
                <el-button @click="addProduct">添加资产</el-button>
              </template>

              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除资产</el-button
                >
              </template>
              <template v-slot:filter-productCodeScan>
                <ScanInputBox
                  :query="scanInfo.query"
                  :api="inventoryLossOrderDetailScan"
                  @callback="onCallBackScanData"
                />
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="false"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="true"
                  :row-class-name="tableRowClassName"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-assetName="scope">
                    <span
                      class="slip-edit"
                      @click="showAssetDetail(scope.row)"
                      >{{ scope.row.assetName }}</span
                    >
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>

    <!--资产选择-->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :api="getInventoryLossOrderDetailCustomizeListPage"
      tableKey="assetManageAssetInventoryLossDetail-com.slip.spd.entity.vo.asset.AssetInventoryLossOrderDetailVO"
      :check-box="true"
      @callback="callBackAsset"
    />
    <!-- 详情页 -->
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
  </div>
</template>
<script setup>
import { getCustomizeSetting } from '@/api/customize'
import {
  assetDealDetailCustomizeListAll,
  getAssetDealById,
  createAssetDeal,
  createAssetDealAndSave,
  submitAssetDeal,
  updateAssetDeal,
  inventoryLossOrderDetailScan,
  getInventoryLossOrderDetailCustomizeListAll,
  getInventoryLossOrderDetailCustomizeListPage,
} from '@/api/asset.js'
import { getCurrentFiscalPeriod } from '@/api/core.js'
import ScanInputBox from './ScanInputBox'

const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps([
  'visible',
  'title',
  'id',
  'lossId',
  'inventoryLocation',
  'lossNo',
  'type',
  'flowFormType',
])
const scanInfo = ref({
  query: {
    orderId: props.lossId,
    useDeptIdMult: '',
    depotId: '',
  },
})
const formInfo = ref({
  ref: null,
  data: {
    dealType: 2,
    position: Number(props.inventoryLocation),
  },
  fieldList: [
    {
      label: '处置类型',
      value: 'dealType',
      type: 'select-model',
      checkDefault: true,
      disabled: true,
      code: 'asset_deal_type',
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      labelTip: '',
      TimePickerOptions: {},
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
    {
      label: '所在位置',
      value: 'position',
      type: 'radio-model',
      code: 'asset_inventory_location',
      disabled: true,
      event: 'position',
    },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'input',
      disabled: true,
      show: false,
    },
    {
      label: '仓库',
      value: 'depotName',
      type: 'input',
      disabled: true,
      show: false,
    },
  ],
  rules: {
    businessDate: [
      {
        required: true,
        message: '请选择业务日期',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '120px',
})
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        value: props.id,
      },
    },
  },
  list: [
    {
      type: 'slot',
      value: 'addProduct',
    },
    {
      type: 'slot',
      value: 'removeProduct',
    },
    {
      type: 'slot',
      value: 'productCodeScan',
    },
  ],
})
const filterLossInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        value: props.lossId,
      },
    },
    queryParams: {
      availableCalcQtyGt: 0,
    },
  },
})
const tableInfo = ref({
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})

const selectAssetInfo = ref({
  visible: false,
  query: {
    queryMap: {
      assetId: {
        queryType: 'NOT_IN',
        value: '',
      },
      orderId: {
        queryType: 'EQUALS',
        value: props.lossId,
      },
      depotId: {
        queryType: 'EQUALS',
        value: '',
      },
    },
    queryParams: {
      useDeptIdMult: '',
      availableCalcQtyGt: 0,
    },
  },
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})

const formRefs = ref([])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})
watch(
  () => props.inventoryLocation,
  (val) => {
    if (val == 1) {
      if (props.id) {
        showFieldListItem(false, 'depotName')
        showFieldListItem(true, 'useDeptName')
      } else {
        showFieldListItem(false, 'depotName')
        showFieldListItem(false, 'useDeptName')
      }
    } else if (val == 2) {
      if (props.id) {
        showFieldListItem(true, 'depotId')
        showFieldListItem(false, 'useDeptId')
      } else {
        showFieldListItem(false, 'depotName')
        showFieldListItem(false, 'useDeptName')
      }
    }
  },
  {
    immediate: true,
  }
)
onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})

setData()
function setData() {
  let obj = {
    dealReason: {
      label: '处置原因',
      value: 'dealReason',
      componentType: 'input',
      maxlength: 200,
      type: 'input',
      show: false,
      hidden: true,
    },
    cleanUpIncome: {
      label: '清理收入',
      value: 'cleanUpIncome',
      type: 'money',
      formatter: proxy.$fn.TripartiteMethod,
      rules: {
        validator: proxy.$validate.positiveMoneyNo,
        trigger: 'blur,change',
      },
      show: false,
      hidden: true,
    },
    cleanUpCost: {
      label: '清理费用',
      value: 'cleanUpCost',
      type: 'money',
      formatter: proxy.$fn.TripartiteMethod,
      rules: {
        validator: proxy.$validate.positiveMoneyNo,
        trigger: 'blur,change',
      },
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
  getFiscalPeriod()
  getLossCustomize()
}

function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.value.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}

function getFiscalPeriod() {
  getCurrentFiscalPeriod(2).then((res) => {
    if (res && res.success) {
      let index = formInfo.value.fieldList.findIndex(
        (item) => item.value === 'businessDate'
      )
      if (index > -1) {
        formInfo.value.fieldList[
          index
        ].labelTip = `当前会计期间：${res.data.name}`
        proxy.$nextTick(() => {
          formInfo.value.fieldList[index].TimePickerOptions = {
            disabledDate(time) {
              return (
                time.getTime() <
                new Date(res.data.startDate).getTime() - 24 * 60 * 60 * 1000
              )
            },
          }
        })
      }
    }
  })
}
// 外部流程组件也需调用
function saveAndSubmit(flowData) {
  save(true, flowData)
}
function save(isSaveAndSubmit, obj = {}) {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = props.id
      ? updateAssetDeal
      : isSaveAndSubmit === true
      ? createAssetDealAndSave
      : createAssetDeal
    let param = {
      ...formInfo.value.data,
      details: tableInfo.value.data,
      sourceType: 109,
      sourceId: props.lossId,
      sourceOrderNo: props.lossNo,
    }
    let paramsData = param
    // 如果是保存并提交
    if (isSaveAndSubmit) {
      if (proxy.$route.query.processInstanceId) {
        api = submitAssetDeal
      }
      paramsData = {
        orderData: param,
        // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
        flowTaskCommentDto: { approvalType: 'submit' },
        processDefinitionKey: 'assetDeal',
        processInstanceId: obj.processInstanceId,
        taskId: obj.taskId,
      }
    }
    api(paramsData).then((res) => {
      if (res && res.success) {
        if (props.type === 'loss') {
          let url = '/asset/assetManage/assetDeal'
          let data = {
            urlType: 1,
            url: url,
          }
          proxy.$router.push(url)
          proxy.$store.dispatch('settings/toPage', data)
          showDialog.value = false
        } else {
          if (proxy.$route.query.processInstanceId) {
            proxy.$router.push(proxy.$route.query.backRouter)
            return
          }
          showDialog.value = false
          emits('returnModify', false)
        }
      }
    })
  })
}

function onCallBackScanData(data, callback) {
  if (data && data.assetCode) {
    data.adjustBefore = data.deprMethodType
    data.adjustBeforeValue = data.deprMethodTypeValue
    data.assetVersion = data.version
    if (tableInfo.value.data) {
      tableInfo.value.data.forEach((item) => {
        item.isChoice = false
      })
      let index = tableInfo.value.data.findIndex(
        (item) => item.assetCode === data.assetCode
      )
      if (index !== -1) {
        callback(true)
      } else {
        tableInfo.value.data.unshift(data)
        callback(false)
      }
    } else {
      tableInfo.value.data.unshift(data)
      callback(true)
    }
  }
}
function addProduct() {
  if (tableInfo.value.data.length) {
    selectAssetInfo.value.query.queryMap.assetId.value = tableInfo.value.data
      .map((item) => item.assetId)
      .toString()
  } else {
    selectAssetInfo.value.query.queryMap.assetId.value = ''
  }
  selectAssetInfo.value.visible = true
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function removeProduct(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function callBackAsset(data) {
  data.forEach((item) => {
    item.adjustBefore = item.deprMethodType
    item.adjustBeforeValue = item.deprMethodTypeValue
    item.assetVersion = item.version
  })
  tableInfo.value.data = data.concat(tableInfo.value.data)
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
function getMain() {
  getAssetDealById(props.id).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data
      formInfo.value.data.position = Number(res.data.position) || 1
      let deptId = res.data.useDeptId === -2 ? '' : res.data.useDeptId || ''

      let depotId = res.data.depotId === -2 ? '' : res.data.depotId || ''
      selectAssetInfo.value.query.queryParams.useDeptIdMult = deptId
      selectAssetInfo.value.query.queryMap.depotId.value = depotId
      scanInfo.value.query.useDeptIdMult = deptId
      scanInfo.value.query.depotId = depotId
    }
  })
}
function getList() {
  assetDealDetailCustomizeListAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
}
function getLossDetail() {
  getInventoryLossOrderDetailCustomizeListAll(filterLossInfo.value.query).then(
    (res) => {
      if (res && res.success) {
        if (res.data && res.data.length) {
          res.data.forEach((item) => {
            item.adjustBefore = item.deprMethodType
            item.adjustBeforeValue = item.deprMethodTypeValue
            item.assetVersion = item.version
          })
        }
        tableInfo.value.data = res.data
      }
    }
  )
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'assetDealOrderMidify-com.slip.spd.entity.vo.asset.AssetDealOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      if (props.id) {
        getMain()
        getList()
      }
    }
  })
}
function getLossCustomize() {
  let param = {
    tableKey:
      'assetManageAssetInventoryLossDetail-com.slip.spd.entity.vo.asset.AssetInventoryLossOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterLossInfo.value.query.customizeUserVO = data
      if (!props.id && props.lossId) {
        getLossDetail()
      }
    }
  })
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>
